import requests
import json
from django.core.exceptions import ValidationError
from utils.tools import *

def csm_user_login(username, password):
    url = '{server}/NimsoftServiceDesk/servicedesk/odata/login'.format(server=CSM_SERVER)
    params = list()
    params.append(('$format', 'JSON'))
    params.append(('username', username))
    params.append(('password', password))

    res = requests.post(url, params=tuple(params))
    kdebug3(res.url)
    kdebug3(res.text)
    if res.status_code != requests.codes.ok:
        res.raise_for_status()

    info = json.loads(res.json()['d']['JSONData'])
    print(info)
    if 'status' not in info:
        raise ValidationError("Missing status")
    if info['status'] == 'success' and 'external_slice' in info:
        return info, res.cookies
    if 'session' in info:
        csm_user_del_sessions(info['session'], res.cookies)
        return csm_user_login(username, password)
    raise ValidationError("Unknown Error")


def csm_user_del_sessions(sessions, cookies):
    url = '{server}/NimsoftServiceDesk/servicedesk/odata/terminateSession?$format=json'.format(server=CSM_SERVER)
    params = list()
    # params.append(('$orderby', 'LastModTimestamp desc'))
    params.append(('$format', 'json'))
    res = requests.get(url, params=tuple(params), cookies=cookies)
    kdebug3(res.url)
    kdebug3(res.text)


def csm_ticket_info(user, MdrElementID, MdrProdInstance, MdrProduct):
    url = "{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/Ticket" \
          "(MdrElementID='{MdrElementID}',MdrProdInstance='{MdrProdInstance}'," \
          "MdrProduct='{MdrProduct}')".format(server=CSM_SERVER,
                                              sid=user.csm_slice_id,
                                              MdrElementID=MdrElementID,
                                              MdrProdInstance=MdrProdInstance,
                                              MdrProduct=MdrProduct)
    params = list()
    # params.append(('$orderby', 'LastModTimestamp desc'))
    params.append(('$format', 'json'))
    params.append(('categorytype', 'list'))
    params.append(('$expand', 'HasCustomFieldMetadata,HasAutomatedFulfillmentDetails'))
    params.append(('parent_entity_key', MdrElementID))
    params.append(('fetch_for_related_tickets', 'false'))
    params.append(('fetch_for_related_cis', 'false'))
    params.append(('fetch_for_related_ci', 'false'))
    params.append(('recentactivity', 'true'))
    params.append(('archived', 'no'))
    # params.append(('CTGREQUEST', 'TRUE'))
    # params.append(('_dc', '1504059926934'))
    # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
    # params.append(('$inlinecount', 'allpages'))

    retried = False
    while True:
        cookies = user.getCookie()
        res = requests.get(url, params=tuple(params), cookies=cookies)
        kdebug3(res.url)
        kdebug3(res.text)
        if retried:
            break
        if res.status_code == requests.codes.unauthorized:
            user.refreshCookie()
            retried = True
            continue
        break
    if res.status_code != requests.codes.ok:
        res.raise_for_status()
    return res.json()['d']


def csm_service_request_info(user, MdrElementID, MdrProdInstance, MdrProduct):
    url = "{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/ServiceRequest" \
          "(MdrElementID='{MdrElementID}',MdrProdInstance='{MdrProdInstance}'," \
          "MdrProduct='{MdrProduct}')".format(server=CSM_SERVER,
                                              sid=user.csm_slice_id,
                                              # sid=MdrProdInstance,
                                              MdrElementID=MdrElementID,
                                              MdrProdInstance=MdrProdInstance,
                                              MdrProduct=MdrProduct)
    params = list()
    params.append(('$orderby', 'HasTicket/LastModTimestamp desc,IsConnectedTo/CreationTimestamp desc'))
    params.append(('$format', 'json'))
    params.append(('categorytype', 'list'))
    params.append(('$expand', 'HasCustomFieldMetadata,HasAutomatedFulfillmentDetails'))
    params.append(('parent_entity_key', MdrElementID))
    params.append(('fetch_for_related_tickets', 'false'))
    params.append(('fetch_for_related_cis', 'false'))
    params.append(('fetch_for_related_ci', 'false'))
    params.append(('recentactivity', 'true'))
    params.append(('archived', 'no'))

    retried = False
    while True:
        cookies = user.getCookie()
        res = requests.get(url, params=tuple(params), cookies=cookies)
        kdebug3(res.url)
        # kdebug3(res.text)
        if retried:
            break
        if res.status_code == requests.codes.unauthorized:
            user.refreshCookie()
            retried = True
            continue
        break
    if res.status_code != requests.codes.ok:
        res.raise_for_status()
    return res.json()['d']
